package com.tx.studentManager.service;

import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Hibernate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.tx.studentManager.dao.UserDao;
import com.tx.studentManager.qo.UserQO;
import com.tx.studentManager.model.Role;
import com.tx.studentManager.model.User;
import com.tx.studentManager.utils.ReflectUtils;

@Transactional
@Service
public class UserService extends BaseService<User, Integer, UserDao, UserQO>{
	@Autowired
	private UserDao userDao;

	private Logger logger=Logger.getLogger(UserService.class);
	
	@Override
	protected UserDao getDao() {
		return userDao;
	}

	public User getUserByUserName(String userName) {
		List<User>list=userDao.findBy("userName", userName);
		if (list==null||list.size()<=0) {
			return null;
		}
		return list.get(0);
	}

	public User registeUser(User user){
		user.setCreateDate(new Date());
		return super.insert(user);
	}

	/**
	 * 覆盖基类保存方法，当创建时间未指定时，自动添加创建时间
	* @param user
	* @return
	* @see com.tx.studentManager.service.BaseService#insert(com.tx.studentManager.model.BaseModel)
	 */
	@Override
	public User insert(User user) {
		if (user.getCreateDate()==null) {
			user.setCreateDate(new Date());
		}
		return super.insert(user);
	}

	/**
	 * 
	* 指定是否加载用户角色
	* @param id 用户ID
	* @param isInit 是否加载用户角色
	* @return
	 */
	public User findById(Integer id,boolean isInit) {
		User user=super.findById(id);
		if (user!=null&&isInit) {
			Hibernate.initialize(user.getRole());
		}
		return user;
	}

	/**
	 * 只更新不为空的字段
	* @param model
	* @return
	* @see com.tx.studentManager.service.BaseService#update(com.tx.studentManager.model.BaseModel)
	 */
	public boolean updateNotNull(User updateUser) {
		if (updateUser.getUserId()==null) {
			logger.info("update object User failure,userId can not null");
			return false;
		}
		User user=findById(updateUser.getUserId(),true);
		ReflectUtils.copyFields(updateUser, user);
		user.setRole(updateUser.getRole());
		return super.update(user);
	}

	/**
	 * 
	*更新用户的角色，使用sql
	* @param user
	* @param role
	* @return
	 */
	public boolean updateUserRole(User user,Role role){
		Integer userId=user.getUserId();
		user=findById(userId, true);
		Integer roleId=role.getRoleId();
		String sql="UPDATE `users_roles` SET `roleId`='"+roleId+"' WHERE (`userId`='"+userId+"')";
		int result=getDao().batchExecuteWithSql(sql);
		if (result>0) {
			return true;
		}else {
			return false;
		}
	}
	
}
